import {SetStorage, API_RECEIVE_DATA} from "./common.js";

// 监听微信文章发布接口的请求
chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    if (details.url.includes('/cgi-bin/appmsgpublish')) {
    //   console.log('监听到微信数据请求：');
    //   console.log('URL:', details.url);
      
      // 解析URL参数
      const urlObj = new URL(details.url);
      const param = Object.fromEntries(urlObj.searchParams.entries());

      // 检查fakeid是否存在且不为空
      if (param.fakeid && param.fakeid.trim() !== '') {
        // 保存到local storage，使用wx_request_param作为key
        console.log("监听到公众号数据请求", param.fakeid);
        SetStorage("wx_request_param", param);
      } else {}
    }
  },
  {urls: ["https://mp.weixin.qq.com/*"]},
  ["requestBody"]
);

/**
 * @title 接收popup.js传递来的信息
 * @author start2004
 * @since 2024-09-23
 */
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.action === "save-weixin-data") {
        fetch(API_RECEIVE_DATA, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                data: JSON.stringify(message.data)
            })
        })
        .then(response => response.json())
        .then(result => {
            console.log('数据提交成功:', result);
            sendResponse({success: true});
        })
        .catch(error => {
            console.error('数据提交失败:', error);
            sendResponse({success: false, error});
        });
        
        return true; // 保持消息通道开放，等待异步操作完成
    }
    return false;
});